package com.insight.modules.system.entity;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.yuanqiao.insight.acore.depart.entity.SysDepart;
import com.yuanqiao.insight.common.constant.enums.ResultCode;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.aspect.annotation.Dict;
import com.insight.common.util.PasswordUtil;
import com.insight.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysUsers implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * id
     */
    @TableId(type = IdType.ASSIGN_ID)
    private String id;

    /**
     * 登录账号
     */
    @Excel(name = "用户账号", width = 15)
    private String username;

    /**
     * 真实姓名
     */
    @Excel(name = "用户姓名", width = 15)
    private String realname;

    /**
     * 密码
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;

    /**
     * md5密码盐
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String salt;

    /**
     * 头像
     */
    @Excel(name = "头像", width = 15, type = 2)
    private String avatar;

    /**
     * 生日
     */
    @Excel(name = "生日", width = 15, format = "yyyy-MM-dd")
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    /**
     * 性别（1：男 2：女）
     */
    @Excel(name = "性别", width = 15, dicCode = "sex")
    @Dict(dicCode = "sex")
    private Integer sex;

    /**
     * 电子邮件
     */
    @Excel(name = "电子邮件", width = 15)
    private String email;

    /**
     * 电话
     */
    @Excel(name = "手机号码", width = 15)
    private String phone;

    /**
     * 部门code(当前选择登录部门)
     */
    private String orgCode;

    /**
     * 部门名称
     */
    @Excel(name = "部门", width = 15)
    private transient String orgCodeTxt;

    @TableField(exist = false)
    private List<SysDepart> allocateOrgList;

    @TableField(exist = false)
    private List<String> exceptUsernameList;

    /**
     * 状态(1：正常  2：冻结 ）
     */
    @Excel(name = "状态", width = 15, dicCode = "user_status")
    @Dict(dicCode = "user_status")
    private Integer status;

    /**
     * 删除状态（0，正常，1已删除）
     */
    @Excel(name = "删除状态", width = 15, dicCode = "del_flag")
    @TableLogic
    private Integer delFlag;

    /**
     * 工号，唯一键
     */
    @Excel(name = "工号", width = 15)
    private String workNo;

    /**
     * 职务，关联职务表
     */
    @Excel(name = "职务", width = 15, dictTable = "sys_position", dicText = "name", dicCode = "code")
    @Dict(dictTable = "sys_position", dicText = "name", dicCode = "code")
    private String post;

    /**
     * 座机号
     */
    @Excel(name = "座机号", width = 15)
    private String telephone;

    /**
     * 创建人
     */
    private String createBy;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 更新人
     */
    private String updateBy;

    /**
     * 更新时间
     */
    private Date updateTime, locksTime;
    /**
     * 同步工作流引擎1同步0不同步
     */
    private Integer activitiSync;

    /**
     * 身份（0 普通成员 1 上级）
     */
    @Excel(name = "（1普通成员 2上级）", width = 15)
    private Integer userIdentity;

    /**
     * 负责部门
     */
    @Excel(name = "负责部门", width = 15, dictTable = "sys_depart", dicText = "depart_name", dicCode = "id")
    @Dict(dictTable = "sys_depart", dicText = "depart_name", dicCode = "id")
    private String departIds;

    /**
     * 多租户id配置，编辑用户的时候设置
     */
    private String relTenantIds;

    /**
     * 设备id uniapp推送用
     */
    private String clientId;
    /**
     * 身份证号，盛事通定制使用
     */
    private String cardId;

    /**
     * 内蒙流程使用  优先级
     */
    @TableField(exist = false)
    private Double priority;
    /**
     * 服务商与用户关联表id
     */
    @TableField(exist = false)
    private String providerUserId;

    /**
     * 个人中心的标签
     */
    private Integer locks;

    @TableField(exist = false)
    private String roleName;

    /**
     * 用户角色
     */
    @TableField(exist = false)
    private String roleCodes;
    /**
     * 是否开启三员
     */
    @TableField(exist = false)
    private Integer isThreePowers;
    @TableField(exist = false)
    private Integer isThreePowerUser;

    public static SysUsers build(JSONObject user) {
        SysUsers sysUsers = new SysUsers();
        final String id = user.getStr("id");
        String account = user.getStr("account");
        //<!--用户信任号-->
        sysUsers.setId(id);
        //<!--用户姓名-->
        sysUsers.setRealname(user.getStr("name"));
        //<!--用户所属机构标识-->
        //sysUsers.setDepartIds(user.getStr("did"));
        //<!--用户排序号-->
        //sysUsers.setWorkNo(user.getStr("dorder"));
        //<!--用户所属机构编码-->
        sysUsers.setOrgCode(user.getStr("dcode"));
        //<!--用户性别1:男，0：女-->
        final Integer sexual = user.getInt("sexual");
        sysUsers.setSex(sexual == 1 ? 1 : 2);
        //<!--用户职务-->
        //String duty = "";
        //<!--用户岗位-->
        //String post = "";
        //<!--用户账号-->
        //<usertype/>
        //<!--用户类型UT01：个人证书用户，UT02：法人证书用户-->
        //<grade>秘密</grade>
        //<!--安全邮箱-->
        final String mail = user.getStr("mail");
        sysUsers.setEmail(StringUtils.isBlank(mail) ? null : mail);

        return sysUsers;
    }

    public static SysUsers build(com.alibaba.fastjson.JSONObject user) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setId(user.getString("userid").replace("-", ""));
        sysUsers.setUsername(user.getString("account"));
        sysUsers.generatePwd("123456");
        sysUsers.setRealname(user.getString("fullname"));
        final Integer sexual = user.getInteger("sex");
        sysUsers.setSex(sexual == 0 ? 1 : 2);
        sysUsers.setEmail(user.getString("userEmail"));
        sysUsers.setPhone(user.getString("mobile"));
        sysUsers.setStatus(1);
        sysUsers.setDelFlag(user.getInteger("isDelete"));
        //sysUsers.setWorkNo(user.getString("orderId"));
        return sysUsers;
    }

    public static SysUsers buildZJGUser(com.alibaba.fastjson.JSONObject user) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setId(user.getString("id"));
        sysUsers.setUsername(user.getString("account"));
        sysUsers.generatePwd("123456");
        sysUsers.setRealname(user.getString("name"));
        sysUsers.setSex(0);
        sysUsers.setStatus(1);
        sysUsers.setDelFlag(0);
        //sysUsers.setWorkNo(user.getString("userNo"));
        sysUsers.setDepartIds(user.getString("orgId"));
        return sysUsers;
    }

    public static SysUsers buildUser(String username, String password, String realName,String phone) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setUsername(username);
        sysUsers.setPhone(phone);
        sysUsers.setRealname(realName);
        sysUsers.generatePwd(password);
        sysUsers.setRealname(username);
        sysUsers.setSex(0);
        sysUsers.setStatus(1);
        sysUsers.setDelFlag(0);
        sysUsers.setUserIdentity(1);
        //sysUsers.setWorkNo(user.getString("userNo"));
        sysUsers.setDepartIds("");
        return sysUsers;
    }

    public void generatePwd(String password) {
        //<!--用户密码-->
        if (StringUtils.isBlank(password)) {
            //密码是空的,使用用户名作为密码
            password = this.getUsername();
        }
        String salt = oConvertUtils.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(this.getUsername(), password, salt);
        this.setSalt(salt);
        this.setPassword(passwordEncode);
    }

    public static ResultCode verificationUser(JSONObject user) {
        //<!--用户信任号-->
        final String id = user.getStr("id");
        if (StringUtils.isEmpty(id)) {
            log.error("缺少用户信任号");
            return ResultCode.CODE_801;
        }
        //<!--用户姓名-->
        final String name = user.getStr("name");
        if (StringUtils.isEmpty(name)) {
            log.error("缺少用户姓名");
            return ResultCode.CODE_801;
        }
        return ResultCode.CODE_1;
    }

    public static String generateAccount(String realName) {
        char[] charArray = realName.toCharArray();
        StringBuilder account = new StringBuilder();
        for (char c : charArray) {
            account.append(PinyinUtil.getPinyin(c));
        }
        return account.toString();
    }

}
